import { memo, useEffect, useState, useMemo } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Card, Form, Input, Button } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { fetchLogin } from "@/store/modules/user";
import { useMessage } from "@/hooks/useMessage";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { getCaptcha } from "@/apis/captcha";
import { runes } from 'runes2';
// import BG from "@/utils/BG";
import style from "./index.module.less";
import { showMessage } from "@/store/modules/message";
import { throttle } from "@/utils/debounceThrottle";

const Login = () => {
    const { success, error, warn, contextHolder } = useMessage()
    const { message, type, visible } = useSelector(state => state.message)
    const [captchaImage, setCaptchaImage] = useState(null);
    const [username, setUsername] = useState('');
    const [loading, setLoading] = useState(false);
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const location = useLocation();

    const captcha = async (username) => {
        if (!username) {
            error({
                content: '请先输入用户名'
            })
            return;
        }
        
        setLoading(true);
        try {
            const res = await getCaptcha(username)
            if (res.code === 200 && res.data) {
                // 将Base64字符串转换为图片URL
                const imageUrl = `data:image/png;base64,${res.data}`;
                setCaptchaImage(imageUrl);
                success({
                    content: '验证码获取成功'
                })
            } else {
                error({
                    content: res.msg || '获取验证码失败'
                })
            }
        } catch (e) {
            console.error('验证码获取错误:', e);
            error({
                content: '获取验证码失败'
            })
        } finally {
            setLoading(false);
        }
    }

    const onFinish = async (values) => {
        try {
            await dispatch(fetchLogin(values));
            dispatch(showMessage({ message: '登录成功', type: 'success' }))
            navigate('/home')
        } catch (e) {
            console.error('登录错误:', e);
            if (e.message === 'Captcha error.') {
                error({
                    content: '验证码错误，请重新输入'
                })
            } else {
                error({
                    content: e.message || '账号或密码错误！'
                })
            }
        }
    };

    const throttledOnFinish = useMemo(() => throttle(onFinish, 1000), [onFinish]);
    const throttledCaptcha = useMemo(() => throttle(captcha, 1000), [captcha, username]);
    const handleUsernameChange = (e) => {
        setUsername(e.target.value);
    };

    useEffect(() => {
        // 如果是注册页跳转过来的，不显示“退出成功”
        // 只在客户端执行，避免 SSR 错误
        if (typeof window === 'undefined') return;
        
        if (location.state?.fromRegister) return;
    
        if (visible && message === '退出成功') {
            success({
                content: message
            })
        } else if (visible && type === 'warn') {
            warn({
                content: message
            })
        }
    }, [visible, message, type, location.state])

    return (
        <div>
            {contextHolder}
            <div className={style.login}>
                <Card className={style.loginCard}>
                    <div className={style.logo}>CoDoc</div>
                    <Form onFinish={throttledOnFinish} validateTrigger="onBlur">
                        <Form.Item
                            name="username"
                            rules={[
                                {
                                    required: true,
                                    message: "请输入账号",
                                },
                            ]}
                        >
                            <Input
                                prefix={<UserOutlined className="site-form-item-icon" />}
                                size="large"
                                placeholder="请输入账号"
                                className={style.logoInput}
                                onChange={handleUsernameChange}
                            />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            rules={[
                                {
                                    required: true,
                                    message: "请输入密码",
                                },
                            ]}
                        >
                            <Input.Password
                                prefix={<LockOutlined className="site-form-item-icon" />}
                                size="large"
                                placeholder="请输入密码"
                                className={style.logoInput}
                            />
                        </Form.Item>
                        <Form.Item style={{
                            marginBottom: 0,
                        }}>
                            <Form.Item
                                name='captcha'
                                style={{
                                    display: 'inline-block',
                                    marginRight: '20px',
                                    width: 210
                                }}
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入验证码",
                                    },
                                ]}
                            >
                                <Input
                                    count={{
                                        show: true,
                                        max: 5,
                                        strategy: (txt) => runes(txt).length,
                                        exceedFormatter: (txt, { max }) => runes(txt).slice(0, max).join('')
                                    }}
                                />
                            </Form.Item>
                            {captchaImage && <img src={captchaImage} alt="captcha" className={style.img} onClick={() => throttledCaptcha(username)} />}
                        </Form.Item>
                        <Form.Item>
                            <Button 
                                type="primary" 
                                size="large" 
                                block
                                disabled={!username.trim()}
                                loading={loading}
                                onClick={() => throttledCaptcha(username)}
                                style={{ marginBottom: 16 }}
                            >
                                获取验证码
                            </Button>
                            <Button type="primary" htmlType="submit" size="large" block>
                                登录
                            </Button>
                        </Form.Item>
                    </Form>
                    <div style={{ textAlign: "center" }}>
                        没有账号？
                        <span
                            style={{ color: "#1677ff", cursor: "pointer", marginLeft: 4 }}
                            onClick={() => {
                                navigate("/register")
                                console.log("点击了注册")
                            }}
                        >
                            去注册
                        </span>
                    </div>
                </Card>
            </div>
            {/* <BG /> */}
        </div>
    );
};

export const MemoLogin = memo(Login);
